package com.news.model;

import hibernate.util.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import java.util.*;

public class NewsDAO  implements NewsDAO_interface{
		
		private static final String GET_ALL_STMT = "from NewsVO order by time desc";

		@Override
		public void insert(NewsVO newsVO) {
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			try {
				session.beginTransaction();
				session.saveOrUpdate(newsVO);
				session.getTransaction().commit();
			} catch (RuntimeException ex) {
				session.getTransaction().rollback();
				throw ex;
			}
		}

		@Override
		public void update(NewsVO newsVO) {
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			try {
				session.beginTransaction();
				//session.saveOrUpdate(newsVO);
				Query query = session.createQuery("update NewsVO set title=?,content=?,time=? where news_id=?");
				query.setParameter(0, newsVO.getTitle());
				query.setParameter(1, newsVO.getContent());
				query.setParameter(2, newsVO.getTime());
				query.setParameter(3, newsVO.getNews_id());
				System.out.print(newsVO.getTime());
				query.executeUpdate();
				session.getTransaction().commit();
			} catch (RuntimeException ex) {
				session.getTransaction().rollback();
				throw ex;
			}
		}

		@Override
		public void delete(Integer news_id) {
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			try {
				session.beginTransaction();
				NewsVO newsVO = (NewsVO) session.get(NewsVO.class, news_id);
				session.delete(newsVO);
				session.getTransaction().commit();
			} catch (RuntimeException ex) {
				session.getTransaction().rollback();
				throw ex;
			}
		}

		@Override
		public NewsVO findByPrimaryKey(Integer news_id) {
			NewsVO newsVO = null;
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			try {
				session.beginTransaction();
				newsVO = (NewsVO) session.get(NewsVO.class, news_id);
				session.getTransaction().commit();
			} catch (RuntimeException ex) {
				session.getTransaction().rollback();
				throw ex;
			}
			return newsVO;
		}

		@Override
		public List<NewsVO> getAll() {
			List<NewsVO> list = null;
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			try {
				session.beginTransaction();
				Query query = session.createQuery(GET_ALL_STMT);
				list = query.list();
				session.getTransaction().commit();
			} catch (RuntimeException ex) {
				session.getTransaction().rollback();
				throw ex;
			}
			return list;
		}
	
}
